package com.gombe.credit.app.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import android.view.View
import com.gombe.credit.app.R
import com.gombe.credit.app.base.app.GombeCreditActivityStackManager
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.ActGombeCreditPayStatusPageBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/27 17:04
 * @Annotation：PIN 支付结果处理中
 */
class ActGombeCreditPayStatus: CommonActivity() {
    lateinit var binding: ActGombeCreditPayStatusPageBinding
    //三方订单id
    private var thirdOrderId = ""

    //倒计时
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 30
    companion object {
        private const val INTENT_KEY_ORDER_ID = "thirdOrderId"
        private const val INTENT_KEY_REPAY_DATE = "repayDate"
        fun start(context: Context,orderId: String,repayDate: String) {
            val intent = Intent(context, ActGombeCreditPayStatus::class.java)
            intent.putExtra(INTENT_KEY_ORDER_ID, orderId)
            intent.putExtra(INTENT_KEY_REPAY_DATE, repayDate)
            context.startActivity(intent)
        }
    }

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditPayStatusPageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditBackBtnRes(R.mipmap.gombe_credit_image_back_black_icon)
        setGombeCreditRightBtnRes(R.mipmap.gombe_credit_image_customer_black_icon)
        setGombeCreditTextTitle(getString(R.string.gombe_credit_pay_status_title))
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
        initGombeCreditPaySatusRefreshView()
        binding.payStatusLayout.visibility = View.INVISIBLE
    }

    override fun initGombeCreditListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Pin Payment Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"Pin Payment Page")
            }
        })

        //还款中 刷新
        binding.buttonUpdateStatus.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_PIN_PROCESS_PAYMENT_UPDATE,"TransactionId：${thirdOrderId}")
                loadGombeCreditPayStatusAction()
            }
        })
        //成功 - 再次申请
        binding.buttonApplyAgain.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_PIN_SUCCESS_APPLY_AGAIN,"TransactionId：${thirdOrderId}")
                showOrderPaySuccessAction()
            }
        })
        //失败 - 重新发起支付
        binding.buttonMakeAgain2.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_PIN_FAILED_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
                onGombeCreditPayAction()
            }
        })
        //还款中 - 重新发起支付
        binding.buttonMakeAgain1.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_PIN_PROCESS_PAYMENT_AGAIN,"TransactionId：${thirdOrderId}")
                onGombeCreditPayAction()
            }
        })
    }

    override fun takeGombeCreditData() {
        thirdOrderId = takeGombeCreditThirdOrderId()
        loadGombeCreditPayStatusAction()
    }

    /* 初始化刷新 */
    private fun initGombeCreditPaySatusRefreshView() {
        binding.pinRefreshView.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.pinRefreshView.setOnRefreshListener {
            loadGombeCreditPayStatusAction()
        }
    }


    /**
     * 支付成功 - 跳转到可申请列表
     */
    private fun showOrderPaySuccessAction(){
        //刷新流程
        publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        //返回首页
        publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_SHOW_HOME))
        GombeCreditActivityStackManager.finishAllActivity(ActGombeCreditMain::class.java)
    }

    /**
     * 三方订单id
     */
    private fun takeGombeCreditThirdOrderId(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_ORDER_ID).toString()
    }

    /**
     * 还款日期
     */
    private fun takeGombeCreditRepayDate(): String {
        if (intent.extras == null){
            return ""
        }
        return intent.extras?.getString(INTENT_KEY_REPAY_DATE).toString()
    }


    /**
     * PIN 通用View
     */
    fun showGombeCreditStatusCommonView(data: JSONObject) {
        binding.textPayAmount.text = data.optString("realRepayAmount","")
//        binding.textUnit.text = data.optString("")
        binding.textPaymentDate.text = String.format(getString(R.string.gombe_credit_pay_status_payment_date_before),takeGombeCreditRepayDate())
        binding.textPayOrderId.text = data.optString("transactionId","")
        binding.payStatusLayout.visibility = View.VISIBLE
    }

    /**
     * PIN 支付成功
     */
    fun showGombeCreditPayStatusSuccessView(data: JSONObject) {
        binding.imagePayStatus.setImageResource(R.mipmap.gombe_credit_image_status_disbursing_icon)
        binding.buttonUpdateStatus.visibility = View.GONE
        binding.textPayStatus.text = getString(R.string.gombe_credit_pay_status_payment_awesome)
        binding.textPayStatus.visibility = View.VISIBLE
        binding.textPayStatusTips.text = getString(R.string.gombe_credit_pay_status_payment_success_tips)
        binding.textPayStatusTips.visibility = View.VISIBLE
        binding.textTransactionId.text = getString(R.string.gombe_credit_pay_status_pay_transaction_id)
        binding.payIdLayout.visibility = View.VISIBLE
        binding.processedLayout.visibility = View.GONE
        binding.successLayout.visibility = View.VISIBLE
        binding.textPaySuccessTime.text = data.optString("realRepayTime","")
        binding.failedLayout.visibility = View.GONE

        binding.payStatusTipsLayout.visibility = View.GONE

        binding.textPayReason.visibility = View.GONE
        binding.buttonMakeAgain1.visibility = View.GONE
        binding.buttonMakeAgain2.visibility = View.GONE
        binding.buttonApplyAgain.visibility = View.VISIBLE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付失败
     */
    @SuppressLint("SetTextI18n")
    fun showGombeCreditPayStatusFailedView(data: JSONObject) {
        binding.imagePayStatus.setImageResource(R.mipmap.gombe_credit_image_status_rejected_icon)
        binding.buttonUpdateStatus.visibility = View.GONE
        binding.textPayStatus.text = "${getString(R.string.gombe_credit_pay_status_failed_title)}~"
        binding.textPayStatus.visibility = View.VISIBLE
        val failReason = data.optString("failReason","")
        if (failReason.isNotEmpty()){
            binding.textPayStatusTips.text = String.format(getString(R.string.gombe_credit_pay_status_failed_reason_failure),failReason)
            binding.textPayStatusTips.visibility = View.VISIBLE
        } else {
            binding.textPayStatusTips.visibility = View.GONE
        }
        binding.textTransactionId.text = getString(R.string.gombe_credit_pay_status_pay_id)
        binding.payIdLayout.visibility = View.VISIBLE
        binding.processedLayout.visibility = View.GONE
        binding.successLayout.visibility = View.GONE
        binding.failedLayout.visibility = View.VISIBLE
        binding.textPayFailedTime.text = data.optString("failedTime")

        binding.payStatusTipsLayout.visibility = View.VISIBLE
        binding.textReasonTips.text = getString(R.string.gombe_credit_pay_status_failed_reason_title)
        binding.textPayReason.text = getString(R.string.gombe_credit_pay_status_failed_reason)

        binding.buttonMakeAgain1.visibility = View.GONE
        binding.buttonMakeAgain2.visibility = View.VISIBLE
        binding.buttonApplyAgain.visibility = View.GONE

        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
    }

    /**
     * PIN 支付中
     */
    fun showGombeCreditPayStatusProcessView(data: JSONObject) {
        //是否是审核账号
        val isAdmin = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接进入还款失败
            showGombeCreditPayStatusFailedView(data)
            return
        }
        binding.imagePayStatus.setImageResource(R.mipmap.gombe_credit_image_status_reviewing_icon)
        binding.buttonUpdateStatus.visibility = View.VISIBLE
        binding.textPayStatus.visibility = View.GONE
        binding.textPayStatusTips.visibility = View.GONE
        binding.payIdLayout.visibility = View.GONE
        binding.processedLayout.visibility = View.VISIBLE
        binding.successLayout.visibility = View.GONE
        binding.failedLayout.visibility = View.GONE

        binding.payStatusTipsLayout.visibility = View.VISIBLE
        binding.textReasonTips.text = getString(R.string.gombe_credit_tips)
        binding.textPayReason.text = String.format(getString(R.string.gombe_credit_pay_status_processed_reason),data.optString("realRepayAmount",""))

        binding.buttonMakeAgain1.visibility = View.VISIBLE
        binding.buttonMakeAgain2.visibility = View.GONE
        binding.buttonApplyAgain.visibility = View.GONE

        countdown = 0
        showPinProcessStatus()
        //是否开启倒计时
        if (data.optBoolean("isStartCountdown",true)){
            startCountdownTimer()
        }
    }

    /**
     * 开启倒计时
     */
    private fun startCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 30

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    class MyCountDownTimer(private val act: ActGombeCreditPayStatus, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showPinProcessStatus()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.loadGombeCreditPayStatusAction(false)
        }
    }

    /**
     * 设置按钮状态
     */
    private fun showPinProcessStatus(){
        if (countdown <= 0){
            binding.buttonMakeAgain1.isEnabled = true
            binding.buttonMakeAgain1.text = String.format(getString(R.string.gombe_credit_pay_status_make_payment_again),"")
        } else {
            binding.buttonMakeAgain1.isEnabled = false
            binding.buttonMakeAgain1.text = String.format(getString(R.string.gombe_credit_pay_status_make_payment_again),"(${countdown}s)")
        }
    }

    /**
     * 获取支付状态
     */
    private fun loadGombeCreditPayStatusAction(isStartCountdown: Boolean = true){
        showGombeCreditLoading()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_STATUS_PATH)
            put("thirdOrderId",thirdOrderId)//三方订单id
        }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideGombeCreditLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    obj.put("isStartCountdown",isStartCountdown)
                    if (obj.has("transactionId")){
                        thirdOrderId = obj.optString("transactionId")
                    }
                    showGombeCreditStatusCommonView(obj)
                    // PROCESSING /SUCCEEDED /FAILED
                    val status = obj.optString("status")
                    when(status){
                        "FAILED" -> {
                            showGombeCreditPayStatusFailedView(obj)
                        }
                        "SUCCEEDED" -> {
                            showGombeCreditPayStatusSuccessView(obj)
                        }
                        else -> {
                            showGombeCreditPayStatusProcessView(obj)
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 订单还款
     */
    private fun onGombeCreditPayAction(){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("mobile",GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_MOBILE))
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_MARKET_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideGombeCreditLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null && obj.has("thirdOrderId")){
                    thirdOrderId = obj.optString("thirdOrderId")
                }
                loadGombeCreditPayStatusAction()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun hideGombeCreditLoading() {
        super.hideGombeCreditLoading()
        binding.pinRefreshView.isRefreshing = false
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_PIN_REPAYMENT_START,"TransactionId：${thirdOrderId}")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_PIN_REPAYMENT_END,"TransactionId：${thirdOrderId}")
    }
}